package formServlets;
import java.io.IOException;
import java.io.PrintWriter;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreAttributes;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;

import javax.servlet.http.HttpServlet;

//import guestbook.PMF;

public class  SchoolInfoServlet  extends HttpServlet  {

	/////////////////////////////////////////////////////////////////////
	// doGet forwards the request to doPost, the code does the same thing
	// whether the post method is GET or POST
	////////////////////////////////////////////////////////////////////
	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		getServletContext().getRequestDispatcher("SNSP.html").forward(req, resp);
	}
 
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		////////////////////////////////////////////////////////////////////
		// Get all the cookies from the webpage that called this servlet
		// Check for a cookie called passUsername
		// record that cookie
		////////////////////////////////////////////////////////////////////
		
	/*	Cookie cookies [] = request.getCookies ();
		Cookie myCookie = null;
		if (cookies != null)
		{
			for (int i = 0; i < cookies.length; i++)
			{
				if (cookies [i].getName().equals ("passUsername"))
				{
				myCookie = cookies[i];
				break;
				}
			}
		}
		*/
//		PrintWriter pw = response.getWriter(); 
		
		// Open access to the database
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		
		// Fetch the information from the form submitted by the page that called this servlet
		
		System.out.println("in schoolinfoservlet");
		String country= request.getParameter("country");
		System.out.println(country);
		String state= request.getParameter("stateList");
		if(state.equalsIgnoreCase("add more"))
		{
			state=request.getParameter("stateLabel");
		}
		//String placeId= request.getParameter("placeId");
		String placeId=country+state;
		String schoolId = request.getParameter("schoolId");
		String schoolName = request.getParameter("schoolName");
		String website = request.getParameter("website");
		String totalStudents = request.getParameter("totalStudents");
		
		
		// Place the information fetched from the form into an entity by schoolId
		Entity user = new Entity("SchoolInfo",schoolId);
		user.setProperty("placeId", placeId);
		user.setProperty("schoolId",schoolId);
		user.setProperty("schoolName", schoolName);
		user.setProperty("website", website);
		user.setProperty("totalStudents", totalStudents);
		
		// Put this entity onto the database
		 datastore.put(user);
		
		 
		// get a new entity called placeId
		 
		user = new Entity("placeInfo",placeId);
		PlaceInfo place=new PlaceInfo(country,state);
        
		//////////////////////////////////////////////////////////////////////////////
		// query the database using PlaceInfo (see java)
		// Put in a filter according to placeID.
		// If there are existing place ID's: print out the properties
		// Else put the placeID into the database.
		//////////////////////////////////////////////////////////////////////////////
		Query q = new Query("PlaceInfo");
		q.addFilter("placeId", Query.FilterOperator.EQUAL,place.getPlaceid()  );
		PreparedQuery pq = datastore.prepare(q);
		System.out.println(FetchOptions.Builder.withPrefetchSize(1));
		
		int count=pq.countEntities(FetchOptions.Builder.withPrefetchSize(1));
		System.out.println("number of entries in database with same placeID= "+ count);
		if(count >0)
		{
			try
			{
				Key key = KeyFactory.createKey("PlaceInfo", placeId);
				Entity en=datastore.get(key);
				System.out.print(en.getProperties());
			}
			catch (EntityNotFoundException e) {
				
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		else
		{
			user.setProperty("placeId", place.getPlaceid());
			user.setProperty("country", place.getCountry());
			user.setProperty("state", place.getState());
			datastore.put(user);
		}
		
		try {
			Key key = KeyFactory.createKey("SchoolInfo", schoolId);
			Entity e=datastore.get(key);
			System.out.print(e.getProperties());
			
		} catch (EntityNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		DatastoreAttributes ds=datastore.getDatastoreAttributes();
		DatastoreAttributes.DatastoreType dst= ds.getDatastoreType();
		System.out.print(dst.name());
		
		response.sendRedirect("successfulSignup.html");

	}
 
}
